package com.example.lab.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.lab.entity.LabManagers;
import com.example.lab.entity.Laboratories;
import com.example.lab.mapper.LabManagersMapper;
import com.example.lab.result.PageResult;
import com.example.lab.service.ILabManagersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 实验室管理员关联表 服务实现类
 * </p>
 *
 * @author 布莱恩
 * @since 2025-06-17
 */
@Service
@RequiredArgsConstructor
public class LabManagersServiceImpl extends ServiceImpl<LabManagersMapper, LabManagers> implements ILabManagersService {

    private final LabManagersMapper labManagersMapper;
    private final LaboratoriesServiceImpl laboratoriesService;

    @Override
    public PageResult<LabManagers> getLabManagers(Integer labId, Integer collegeId, Integer page, Integer limit) {

        // 创建对 LabManagers 的查询 Wrapper
        QueryWrapper<LabManagers> queryWrapper = new QueryWrapper<>();

        if (labId != null) {
            queryWrapper.eq("lab_id", labId);
        }
        if (collegeId != null) {
            queryWrapper.eq("college_id", collegeId);
        }

        // 分页查询 LabManagers
        Page<LabManagers> pageResult = labManagersMapper.selectPage(new Page<>(page, limit), queryWrapper);

        return new PageResult<>(
                pageResult.getRecords(),
                pageResult.getTotal(),
                pageResult.getCurrent(),
                pageResult.getSize()
        );
    }

    @Override
    public boolean assignLabManager(LabManagers labManager) {

        // 检查实验室是否启用
        if (!laboratoriesService.isLaboratoryEnabled(labManager.getLabId())) {
            throw new RuntimeException("实验室已禁用，不能分配管理员");
        }

        // 检查实验室是否已经存在管理员
        if (isLabAlreadyManaged(labManager.getLabId())) {
            return false;
        }

        return save(labManager);
    }

    @Override
    public boolean removeLabManager(Integer id) {
        return removeById(id);
    }

    @Override
    public boolean removeByLabId(Integer labId) {
        QueryWrapper<LabManagers> wrapper = new QueryWrapper<>();
        wrapper.eq("lab_id", labId);
        return remove(wrapper);
    }


    /**
     * 检查实验室是否已经被分配
     *
     * 通过查询数据库中是否存在给定实验室ID来判断实验室是否已经被分配
     * 此方法用于确保实验室的唯一性和避免重复分配
     *
     * @param labId 实验室ID，用于查询实验室是否已存在
     * @return 返回一个布尔值，如果实验室已经被分配，则返回true；否则返回false
     */
    @Override
    public boolean isLabAlreadyManaged(int labId) {
        LambdaQueryWrapper<LabManagers> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabManagers::getLabId, labId);
        return count(queryWrapper) > 0;
    }

}
